package com.zhupanlin.zhyl.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhupanlin.zhyl.common.exception.Zhylxception;
import com.zhupanlin.zhyl.common.result.ResultCodeEnum;
import com.zhupanlin.zhyl.hosp.mapper.ScheduleMapper;
import com.zhupanlin.zhyl.hosp.repository.HospitalRepository;
import com.zhupanlin.zhyl.hosp.repository.ScheduleRepository;
import com.zhupanlin.zhyl.hosp.service.DepartmentService;
import com.zhupanlin.zhyl.hosp.service.HospitalService;
import com.zhupanlin.zhyl.hosp.service.ScheduleService;
import com.zhupanlin.zhyl.model.hosp.BookingRule;
import com.zhupanlin.zhyl.model.hosp.Department;
import com.zhupanlin.zhyl.model.hosp.Hospital;
import com.zhupanlin.zhyl.model.hosp.Schedule;
import com.zhupanlin.zhyl.model.vo.hosp.BookingScheduleRuleVo;
import com.zhupanlin.zhyl.vo.hosp.ScheduleOrderVo;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author zhupanlin
 * @version 1.0
 * @description: TODO
 * @date 2024/11/26 9:15
 */
@Service
public class ScheduleServiceImpl extends ServiceImpl<ScheduleMapper, Schedule> implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;

    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private HospitalService hospitalService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 上传排班接口
     *
     * @param paramMap
     */
    @Override
    public void save(Map<String, Object> paramMap) {
        // 校验
        hospitalService.checkSign(paramMap);
        String jsonString = JSONObject.toJSONString(paramMap);
        Schedule schedule = JSONObject.parseObject(jsonString, Schedule.class);

        Schedule scheduleExists = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(), schedule.getHosScheduleId());

        // 判断
        if (scheduleExists != null) {
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
        } else {
            schedule.setCreateTime(new Date());
            schedule.setUpdateTime(new Date());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
        }
        scheduleRepository.save(schedule);

    }

    /**
     * 查询排班接口
     *
     * @param paramMap
     * @return
     */
    @Override
    public Page<Schedule> findPageSchedule(Map<String, Object> paramMap) {
        hospitalService.checkSign(paramMap);
        String hoscode = (String) paramMap.get("hoscode");
        String depcode = (String) paramMap.get("depcode");
        Schedule schedule = new Schedule();
        schedule.setHoscode(hoscode);
        schedule.setDepcode(depcode);
        schedule.setIsDeleted(0);
        schedule.setStatus(1);

        int page = StringUtils.isEmpty(paramMap.get("page")) ? 1 : Integer.parseInt((String)paramMap.get("page"));
        int limit = StringUtils.isEmpty(paramMap.get("limit")) ? 10 : Integer.parseInt((String)paramMap.get("limit"));

        Pageable pageable = PageRequest.of(page, limit);

        // 创建 Example 对象
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase();
        Example<Schedule> example = Example.of(schedule, matcher);

        Page<Schedule> result = scheduleRepository.findAll(example, pageable);
        return result;
    }

    /**
     * 删除排班接口
     *
     * @param paramMap
     */
    @Override
    public void removeSchedule(Map<String, Object> paramMap) {
        hospitalService.checkSign(paramMap);

        String hoscode = (String) paramMap.get("hoscode");
        String hosScheduleId = (String) paramMap.get("hosScheduleId");
        // 查询
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (schedule != null) {
            scheduleRepository.delete(schedule);
        }
    }

    /**
     * 根据医院编号 和 科室编号，查询排班规则数据
     *
     * @param page
     * @param limit
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Map<String, Object> getRuleSchedule(Long page, Long limit, String hoscode, String depcode) {
        // 1. 根据医院编号 和 科室编号进行查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode);

        // 2. 根据工作日期进行分组
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria), // 匹配条件
                Aggregation.group("workDate") // 分组
                        .first("workDate").as("workDate")
                        // 3. 统计号源数量
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                // 排序
                Aggregation.sort(Sort.Direction.DESC, "workDate"),
                // 4. 实现分页
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)
        );
        // 执行
        AggregationResults<BookingScheduleRuleVo> aggResults = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleList = aggResults.getMappedResults();

        // 分组查询的总记录数
        Aggregation totalAgg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );

        AggregationResults<BookingScheduleRuleVo> totalAggResults = mongoTemplate.aggregate(totalAgg, Schedule.class, BookingScheduleRuleVo.class);

        int total = totalAggResults.getMappedResults().size();

        // 把日期对应星期获取
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleList) {
            Date workDate = bookingScheduleRuleVo.getWorkDate();
            String dayOfWeek = getDayOfWeek(new DateTime(workDate));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
        }

        // 设置最终数据，进行返回
        Map<String, Object> result = new HashMap<>();
        result.put("bookingScheduleRuleList", bookingScheduleRuleList);
        result.put("total", total);

        // 获取医院名称
        String hospName = hospitalService.getHospNameByHoscode(hoscode);
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname", hospName);
        result.put("baseMap", baseMap);

        return result;
    }

    /**
     * 根据医院编号、科室编号和工作日期，查询排班详细信息
     *
     * @param hoscode
     * @param depcode
     * @param workDate
     * @return
     */
    @Override
    public List<Schedule> getScheduleDetail(String hoscode, String depcode, String workDate) {
        List<Schedule> scheduleList = scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode, depcode, new DateTime(workDate).toDate());
        String hosname = hospitalService.getHospNameByHoscode(hoscode);
        String depName = departmentService.getDepName(hoscode, depcode);
        // 设置其他值：医院名称，科室名称、周几
        scheduleList.forEach(item -> {
            Map<String, Object> param = item.getParam();
            param.put("hosname", hosname);
            param.put("depName", depName);
            param.put("dayOfWeek", this.getDayOfWeek(new DateTime(item.getWorkDate())));
            packageSchedule(item);
        });
        return scheduleList;
    }

    /**
     * 获取可预约的排班数据
     *
     * @param page
     * @param limit
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Map<String, Object> getBookingScheduleRule(Long page, Long limit, String hoscode, String depcode) {
        Map<String, Object> result = new HashMap<>();
        // 获取预约规则
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        if (hospital == null) {
            throw new Zhylxception(ResultCodeEnum.DATA_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();

        // 获取可预约日期的数据（分页）
        IPage<Date> pageModel = getListDate(page, limit, bookingRule);

        // 获取当前可预约日期
        List<Date> dateList = pageModel.getRecords();

        // 获取可预约日期里面科室的剩余预约数
        Criteria criteria = Criteria.where("hoscode").is(hoscode)
                .and("depcode").is(depcode)
                .and("workDate").in(dateList);

        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate").first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("availableNumber").as("availableNumber")
                        .sum("reservedNumber").as("reservedNumber")
        );

        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> scheduleVoList = aggregationResults.getMappedResults();

        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(scheduleVoList)) {
            scheduleVoMap = scheduleVoList.stream().
                    collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate,
                    BookingScheduleRuleVo -> BookingScheduleRuleVo));
        }

        // 获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for (int i = 0, len = dateList.size(); i < dateList.size(); i++) {
            Date date = dateList.get(i);
            BookingScheduleRuleVo scheduleRuleVo = scheduleVoMap.get(date);
            // 如果当天没有排班医生
            if (scheduleRuleVo == null) {
                scheduleRuleVo = new BookingScheduleRuleVo();
                scheduleRuleVo.setDocCount(0);
                scheduleRuleVo.setAvailableNumber(-1);
            }
            scheduleRuleVo.setWorkDate(date);
            scheduleRuleVo.setWorkDateMd(date);
            // 计算当前日期对应星期
            String dayOfWeek = getDayOfWeek(new DateTime(date));
            scheduleRuleVo.setDayOfWeek(dayOfWeek);
            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if(i == len-1 && page == pageModel.getPages()) {
                scheduleRuleVo.setStatus(1);
            } else {
                scheduleRuleVo.setStatus(0);
            }
            //当天预约如果过了停号时间， 不能预约
            if(i == 0 && page == 1) {
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if(stopTime.isBeforeNow()) {
                    //停止预约
                    scheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(scheduleRuleVo);
        }

        //可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", pageModel.getTotal());
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospitalService.getHospNameByHoscode(hoscode));
        //科室
        Department department =departmentService.getDepartment(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;
    }

    /**
     * 根据排班 id 获取排班数据
     *
     * @param scheduleId
     * @return
     */
    @Override
    public Schedule getSucheduleById(String scheduleId) {
        Schedule schedule = scheduleRepository.findById(scheduleId).get();
        return packageSchedule(schedule);
    }

    /**
     * 根据排班 id 获取预约下单数据
     *
     * @param scheduleId
     * @return
     */
    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        // 获取排班信息
        Schedule schedule = baseMapper.selectById(scheduleId);
        if (schedule == null) {
            throw new Zhylxception(ResultCodeEnum.PARAM_ERROR);
        }

        // 获取预约规则信息
        Hospital hospital = hospitalRepository.getHospitalByHoscode(schedule.getHoscode());
        if (hospital == null) {
            throw new Zhylxception(ResultCodeEnum.PARAM_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();
        if (bookingRule == null){
            throw new Zhylxception(ResultCodeEnum.PARAM_ERROR);
        }

        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospitalService.getHospNameByHoscode(schedule.getHoscode()));
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepName(schedule.getHoscode(), schedule.getDepcode()));
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStartTime(startTime.toDate());

        scheduleOrderVo.setStopTime(stopTime.toDate());
        return scheduleOrderVo;
    }

    /**
     * 更新排班数据 用于 MQ
     *
     * @param schedule
     */
    @Override
    public void update(Schedule schedule) {
        schedule.setUpdateTime(new Date());
        scheduleRepository.save(schedule);
    }

    /**
     * 获取可预约日期分页数据
     * @param page
     * @param limit
     * @param bookingRule
     * @return
     */
    private IPage<Date> getListDate(Long page, Long limit, BookingRule bookingRule) {
        // 获取当天放号时间 yyyy-MM-dd HH:mm:ss
        DateTime releaseTime = getDateTime(new Date(), bookingRule.getReleaseTime());
        // 获取预约周期
        Integer cycle = bookingRule.getCycle();
        // 如果当天放号时间已经过去了，预约周期从后一天开始计算，周期 + 1
        if (releaseTime.isBeforeNow()) {
            cycle += 1;
        }

        // 获取可预约的所有日期，最后一天显示即将放号
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            DateTime curDateTime = new DateTime().plusDays(i);
            String dateString = curDateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateString).toDate());
        }

        // 以为预约周期不同，每页显示7天数据，超过7天进行分页
        List<Date> pageDateList = new ArrayList<>();
        int start = (int) ((page - 1) * limit);
        int end = (int) (page * limit);

        // 如果可以显示数据小于 7，直接显示
        if (end >= dateList.size()) {
            end = dateList.size();
        }
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, 7, dateList.size());
        iPage.setRecords(pageDateList);
        return iPage;
    }

    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " " + timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

    /**
     * 封装排班详情其他值 医院名称、科室名称、日期
     *
     * @param schedule
     * @return
     */
    private Schedule packageSchedule(Schedule schedule) {
        Map<String, Object> param = schedule.getParam();

        return schedule;
    }

    /**
     * 根据日期获取周几数据
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime) {
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()) {
            case DateTimeConstants.SUNDAY:
                dayOfWeek = "周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek = "周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek = "周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek = "周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek = "周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek = "周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek = "周六";
            default:
                break;
        }
        return dayOfWeek;
    }
}
